package com.cell.api.application.netty.utils;

import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 通道hashMap
 * </p>
 *
 * @author zdy
 * @date 2021/11/6
 */
public class ChannelHashMap {

    /**
     * 通道数量
     */
    public static int channelNum = 0;
    /**
     * 存储通道信息
     */
    private static ConcurrentHashMap<String, Channel> channelHashMap = null;

    /**
     * 获取一个ChannelHashMap
     *
     * @return 返回ChannelHashMap对象
     */
    public synchronized static ConcurrentHashMap<String, Channel> getChannelHashMap() {
        if (channelHashMap == null) {
            return channelHashMap = new ConcurrentHashMap<>(100);
        }
        return channelHashMap;
    }

    /**
     * 根据名称返回一个Channel
     *
     * @param name 键值
     * @return Channel对象
     */
    public static Channel getChannelByName(String name) {
        return getChannelHashMap().get(name);
    }

    /**
     * 增加一个Channel
     *
     * @param name    键值
     * @param channel Channel对象
     */
    public static void putChannel(String name, Channel channel) {
        getChannelHashMap().put(name, channel);
        channelNum++;
    }

    /**
     * 移除一个Channel
     *
     * @param name 键值
     * @return 移除是否成功
     */
    public static boolean removeChannelByName(String name) {
        if (getChannelHashMap().containsKey(name)) {
            getChannelHashMap().remove(name);
            return true;
        } else {
            return false;
        }
    }
}
